package run

import (
	"codejy/globalfunc"
	"codejy/store"
	"codejy/utils"
	"fmt"
	"os"
	"path/filepath"
	"strings"
)

func init() {
	globalfunc.RegisterFuncAll("CodejyRun", CodejyRun)
}

// CodejyRun 执行代码 ,isMain是否是主文件如果是主文件那么就会执行代码,否则只会加载函数和类型定义
func CodejyRun(mainFilePath string, isMain bool) {
	defer func() {
		if err := recover(); err != nil {
			store.PrintExecuteCodeRecordLog(store.MainThreadStore, err)
			os.Exit(1)
		}
	}()
	//判断mainThreadid是否为空,如果为空,则创建主线程环境
	if store.MainThreadStore == nil {
		//创建主线程环境
		_, threadStore := store.CreateThread()
		store.MainThreadStore = threadStore
	}

	//获取当前执行代码所在的主目录
	dir, _ := os.Getwd() //获取当前目录
	//设置当前主目录
	store.CurrentExeDir = dir
	utils.DebugLog("当前执行代码所在的主目录", func() {
		fmt.Println(store.CurrentExeDir)
	})
	store.MainFilePath = mainFilePath
	//获取当前主目录
	mainDir := getCurrentMainDir(mainFilePath)
	//设置当前执行代码所在的主目录
	store.MainFileDir = mainDir
	utils.DebugLog("主文件所在的主目录:", func() {
		fmt.Println(store.MainFileDir)
	})
	//获取其他工作目录
	env := getWorkSpaceEnv("CODEJY_OTHER_DIR")
	utils.DebugLog("其他工作目录路径:", func() {
		fmt.Println(env)
	})
	//设置其他工作目录
	store.CurrentOtherDir = env
	CodeScanner(mainFilePath, mainFilePath, isMain)
	if utils.Debug {
		store.PrintExecuteCodeRecordLog(store.MainThreadStore, nil)
	}

}

func getCurrentMainDir(mainFilePath string) string {
	//获取当前主目录
	var mainDir string
	if strings.Contains(mainFilePath, "/") {
		mainDir = mainFilePath[0:strings.LastIndex(mainFilePath, "/")]
	} else if strings.Contains(mainFilePath, "\\") {
		mainDir = mainFilePath[0:strings.LastIndex(mainFilePath, "\\")]
	} else {
		mainDir = "./"
	}
	//如果文件结尾没有系统分隔符那么补充
	if !strings.HasSuffix(mainDir, "/") && !strings.HasSuffix(mainDir, "\\") {
		isAbs := filepath.IsAbs(mainDir)
		if isAbs {
			mainDir = mainDir + string(os.PathSeparator)
		} else {
			mainDir = mainDir + "/"
		}
	}
	return mainDir
}

// 获取系统指定的环境变量
func getWorkSpaceEnv(key string) []string {
	env := os.Getenv(key)
	//去掉空格
	env = strings.TrimSpace(env)
	if env == "" {
		return []string{}
	}
	//以逗号分隔
	envs := strings.Split(env, ",")
	//判断结尾是否有斜杠,如果没有,则添加当前系统的斜杠
	for i := range envs {
		if !strings.HasSuffix(envs[i], "/") && !strings.HasSuffix(envs[i], "\\") {
			envs[i] = envs[i] + string(os.PathSeparator)
		}
	}
	return envs
}
